import numpy as np
import cv2
import caliou

res10_300x300_ssd_iter_140000_fp16 = cv2.dnn.readNetFromCaffe("deploy.prototxt",
                                                              "res10_300x300_ssd_iter_140000_fp16.caffemodel")


# face count
def detect_(image, conf_threshold=0.5):
    pad = 90
    image = cv2.resize(image, (120, 120))
    image = cv2.copyMakeBorder(image, pad, pad, pad, pad, cv2.BORDER_CONSTANT, value=[0, 0, 0])
    (h, w) = image.shape[:2]
    blob = cv2.dnn.blobFromImage(cv2.resize(image, (300, 300)), 1.0,
                                 (300, 300), (104.0, 177.0, 123.0))

    res10_300x300_ssd_iter_140000_fp16.setInput(blob)
    detections = res10_300x300_ssd_iter_140000_fp16.forward()
    bboxes = []
    for i in range(detections.shape[2]):
        confidence = detections[0, 0, i, 2]
        if confidence < conf_threshold:
            continue
        box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
        (startX, startY, endX, endY) = box.astype("int")
        bboxes.append([startX, startY, endX, endY])

    return len(caliou.calculateIoU(bboxes))
